<template>
  <div>
    <el-dialog :title="isEdit? '编辑部门':'添加部门'" :visible="showDialog" @close="close">
      <el-form ref="formDateRef" :model="formDate" :rules="formDateRules">
        <el-form-item label="部门名称" label-width="150px" prop="name">
          <el-input v-model="formDate.name" placeholder="2-10个字符" />
        </el-form-item>
        <el-form-item label="部门编码：" label-width="150px" prop="code">
          <el-input v-model="formDate.code" placeholder="2-10个字符" />
        </el-form-item>
        <el-form-item label="部门负责人：" label-width="150px" prop="managerId">
          <el-select v-model="formDate.managerId" style="width: 100%;" placeholder="请选择负责人">
            <el-option v-for="item in managerList" :key="item.id" :label="item.username" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="活动形式" label-width="150px" prop="introduce">
          <el-input v-model="formDate.introduce" type="textarea" placeholder="1-100个字符" />
        </el-form-item>
        <el-form-item label-width="150px">
          <el-button type="primary" @click="submitForm">{{ isEdit? '编辑':'添加' }}</el-button>
          <el-button @click="close">取 消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { sysUsersimpleRequest, companyRequest, getDepartmentRequest, revampCompanyRequest } from '@/api/department.js'
import { cloneDeep } from 'lodash-es'
export default {
  name: 'Alldialog',
  props: {
    showDialog: Boolean,
    departmentList: {
      type: Array,
      // 这是复杂数据类型的默认值，一般要加上，不然会有黄色警告
      default: () => []
    },
    crrentid: {
      type: [String, Number],
      default: ''
    },
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      managerList: [],
      formDate: {
        name: '',
        code: '',
        managerId: '',
        introduce: '',
        pid: ''
      },
      formDateRules: {
        name: [
          { required: true, message: '请输部门名称', trigger: 'blur' },
          { min: 2, max: 10, message: '部门名称位数在2-10位', trigger: 'blur' },
          { validator: (rule, value, callback) => {
            // 深拷贝在工作中，一般使用lodash这个包
            // 工作中，对于复杂数据类型的修改，尽量要用深拷贝，因为等号赋值的是地址
            let res = cloneDeep(this.departmentList)
            if (this.isEdit) {
              res = res.filter(item => item.id !== this.crrentid)
            }
            if (res.some(item => item.name === value)) {
              callback(new Error('部门名称重复'))
            } else {
              callback()
            }
          }, trigger: ['change', 'blur'] }
        ],
        code: [
          { required: true, message: '请输部门编码', trigger: 'blur' },
          { min: 2, max: 10, message: '部门编码位数在2-10位', trigger: 'blur' },
          { validator: (rule, value, callback) => {
            let res = cloneDeep(this.departmentList)
            if (this.isEdit) {
              res = res.filter(item => item.id !== this.crrentid)
            }
            if (res.some(item => item.code === value)) {
              callback(new Error('部门名称重复'))
            } else {
              callback()
            }
          }, trigger: ['change', 'blur'] }
        ],
        managerId: [
          { required: true, message: '请选择部门负责人', trigger: 'change' }
        ],
        introduce: [
          { required: true, message: '请输部门介绍', trigger: 'blur' },
          { min: 2, max: 10, message: '部门名称位数在1-100位', trigger: 'blur' }
        ]
      }
    }
  },
  // 在事件监听器中监听编辑和添加，如果是编辑就会发送请求，会回返数据
  watch: {
    // 第二次不会回显
    isEdit: function(newVal, oldVal) {
      if (newVal) {
        this.getDepartment()
      }
    }
  },
  created() {
    this.sysUsersimple()
  },
  methods: {
    close() {
      // 这边是利用了sync修饰符
      this.$emit('update:show-dialog', false)
      // 第二次回显把is-edit改为false,关闭的时候把is-edit改为false
      this.$emit('update:is-edit', false)
      this.$refs.formDateRef.resetFields()
      // 当编辑之后，form数据会被污染，新增很多数据，导致下一次新增就会表示参数与后端要的数据不一样 报错
      // 使用$options().data()方法重置form数据
      this.formDate = this.$options.data().formDate
    },
    // 获取部门详情
    async getDepartment() {
      const res = await getDepartmentRequest(this.crrentid)
      this.formDate = res.data
      // console.log(res)
    },
    // 渲染部门负责人
    async sysUsersimple() {
      const res = await sysUsersimpleRequest()
      this.managerList = res.data
      // console.log(res)
    },
    // 提交事件与表单检验
    submitForm() {
      console.log(this.formDate)
      this.$refs.formDateRef.validate(async(valid) => {
        if (valid) {
          // 一个按钮控制两个事件
          if (this.isEdit) {
            await revampCompanyRequest(this.formDate)
          } else {
            await companyRequest({ ...this.formDate, pid: this.crrentid })
          }
          // 添加请求的发送 核心是pid的传值
          // 关闭弹窗
          this.close()
          // 子组件调用父组件的方法，不用传参，利用自定义事件调用
          this.$emit('addSuccess')
          this.$message.success(`${this.isEdit ? '编辑' : '添加'}部门成功`)
        }
      })
    }
  }
}
</script>

<style>

</style>
